import random
from django.views import View
from django.http import HttpResponse, JsonResponse
import logging
from django_redis import get_redis_connection

from . import constants
from verifications.libs.captcha.captcha import captcha
from meiduo_mall.utils.response_code import RETCODE
from celery_tasks.sms.tasks import send_sms_code

# Create your views here.
logger = logging.getLogger('django')

class ImageCodeView(View):
    '''生成验证码图片'''

    def get(self,request,uuid):
        """
        生成验证码图片
        :param request:请求对象
        :param uuid: 验证码图片唯一标示
        :return: 图片
        """

        text,image = captcha.generate_captcha()

        redis_conn = get_redis_connection('verify_code')
        redis_conn.setex('img_%s' % uuid,constants.IMAGE_CODE_REDIS_EXPIRES,text)

        return HttpResponse(image,content_type='image/jpg')


class SMScodeView(View):
    """短信验证"""


    def get(self,request,mobile):
        """

        :param request: 请求对象
        :param mobile: 手机号
        :return: json
        """
        # 验证图片验证码
        image_code_client = request.GET.get('image_code')
        image_code_client = image_code_client.lower()
        uuid = request.GET.get('uuid')

        if not all([image_code_client,uuid]):
            return JsonResponse({'code':RETCODE.NECESSARYPARAMERR,'errmsg':'缺少必要参数'})
        redis_conn = get_redis_connection('verify_code')
        # 验证60秒发送短信标记
        send_flag_mobile = redis_conn.get('sms_%s' % mobile)
        if send_flag_mobile:
            return JsonResponse({'code':RETCODE.THROTTLINGERR,'errmsg':'发送短信太频繁'})
        image_code_server = redis_conn.get('img_%s' % uuid)
        if image_code_server is None:
            return JsonResponse({'code':RETCODE.IMAGECODEERR,'errmsg':'图形验证码失效'})
        try:
            redis_conn.delete('img_%s' % uuid)
        except Exception as e:
            logger.error(e)

        image_code_server = image_code_server.decode().lower()
        if image_code_client != image_code_server:
            return JsonResponse({'code':RETCODE.IMAGECODEERR,'errmsg':'图形验证码输入有误'})

        # 生成短信验证码
        sms_code = '%06d' % random.randint(0,999999)
        logger.info(sms_code)
        # 减少与redis服务器交互次数
        pl = redis_conn.pipeline()
        pl.setex('sms_%s' % mobile,constants.SMS_CODE_REDIS_EXPIRES,sms_code)
        # 保持发送验证码的标记，避免用户频繁发送
        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.execute()
        # 发送短信异步发送
        send_sms_code.delay(mobile,sms_code)

        #CCP().send_template_sms(mobile,[sms_code,constants.SMS_CODE_REDIS_EXPIRES // 60],constants.SEND_SMS_TEMPLATE_ID)


        return JsonResponse({'code':RETCODE.OK,'errmsg':'发送成功'})


